package org.ezplatform.office.meeting.notice.web.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.exception.ValidationException;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.meeting.info.entity.ApplyRecord;
import org.ezplatform.office.meeting.info.service.ApplyRecordService;
import org.ezplatform.office.meeting.info.service.SignedInfoService;
import org.ezplatform.office.meeting.notice.entity.NoticeInfo;
import org.ezplatform.office.meeting.notice.service.NoticeInfoService;
import org.ezplatform.office.meeting.task.service.MeetingTaskInfoService;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName: NoticeInfoController
 * @Description: 会议通知控制类
 * @author: pa
 * @date 2018-03-02 10:29:33
 */
@RestController
@RequestMapping(value = "/api/w/noticeInfoController")
public class NoticeInfoWebApiController extends BaseController<NoticeInfo, String> {

	private final static Logger LOGGER = LoggerFactory.getLogger(NoticeInfoWebApiController.class);
	
	@Autowired
	private NoticeInfoService service;
	
	@Autowired
	private ApplyRecordService applyRecordService;
	
	@Autowired
	private MeetingTaskInfoService meetingTaskInfoService;
	
	@Autowired
	private NoticeInfoService noticeInfoService;
	
	@Autowired
	private SignedInfoService signedInfoService;

	@Override
	protected BaseService<NoticeInfo, String> getEntityService() {
		return service;
	}

	/**
	 * 
	 * @Title: prepareModel
	 * @Description: 初始化数据
	 * @param request
	 * @param model
	 * @param id
	 * @return void
	 * @throws
	 */
	@ModelAttribute
	public void prepareModel(HttpServletRequest request, Model model,
			@RequestParam(value = "id", required = false) String id) {
		super.initPrepareModel(request, model, id);
	}

	/**
     * 
     * @Title: getNoticeInfoList
     * @Description: 获取list数据
     * @param request
     * @return
     * @throws
     */
    @RequestMapping(value = "/getNoticeInfoList", method = RequestMethod.GET)
    public Map<String, Object> getNoticeInfoList(HttpServletRequest request) {
    	LOGGER.debug("-----getNoticeInfoList----");

        Map<String, Object> map = new HashMap<String,Object>();
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String userId = user.getUserId();
        List<Map<String, Object>> remindMap = this.service.getNoticeList(corpId, userId);
        LOGGER.debug("--remindMap.size():"+remindMap.size());
        map.put("remindMap", remindMap);
        int count = this.meetingTaskInfoService.taskInfosCount("0", "", userId, corpId,"");
        map.put("taskCount", count);
        return map;
    }
    /**
     * 我发出的会议
     * @param request
     * @return
     */
    @RequestMapping(value = "/noticeInfoList", method = RequestMethod.GET)
    public Page<Map> findNoticeInfoListByMe(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		String corpId = user.getCorpId();
		List<Map> userL=this.service.findByListNativeQuery("select user_status as userStatus,is_delete as isDelete from sys_user where id='"+userId+"'", "");
		if(userL!=null && userL.size()>0) {
			Map userStatus=userL.get(0);
			if("offDuty".equals(userStatus.get("userStatus"))||"1".equals(userStatus.get("isDelete")+"")) {
				return new PageImpl<Map>(new ArrayList<Map>());
			}
		}
		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("startTime", request.getParameter("startTime"));
		paramMap.put("endTime", request.getParameter("endTime"));
		paramMap.put("meetingName", request.getParameter("meetingName"));
		paramMap.put("boardroomName", request.getParameter("boardroomName"));
		paramMap.put("status", request.getParameter("status"));
		
		return this.service.findNoticeInfoListByMe(pageable, corpId, userId,paramMap);
    }
    
    /**
     * 保存/修改
     *
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/editSave", method = RequestMethod.POST)
    public OperationResult editSave(HttpServletRequest request) {
    	Map failureMap = new HashMap();
    	 
    	try {
    		WebUser user = WebUtils.getCurrentUser();
    		String userId = user.getUserId();
    	    String token = user.getJwtToken();
			String id = ValidateUtils.filter(request.getParameter("id"));
			NoticeInfo entity = this.service.findOne(id);
			if(entity == null) {
				failureMap.put("i18NCode", "oa.meeting.datadelsuccess");
				return OperationResult.buildFailureResult("当前数据已删除",failureMap);
			}
			String applyRecordId = entity.getApplyRecordId();
			if(applyRecordId == null) {
				failureMap.put("i18NCode", "oa.meeting.datadelsuccess");
				return OperationResult.buildFailureResult("当前数据已删除",failureMap);
			}
			String nStatus = ValidateUtils.filter(request.getParameter("nStatus"));
			String attendWay = request.getParameter("attendWay");
			String reason = request.getParameter("reason");
			if(!ValidateUtils.validateComm(reason)) {
				throw new ValidationException("INVALID PARAMETER VALUE");
			}
			if("5".equals(nStatus)) {//代参会人确认参会
				//替换参会人
				ApplyRecord ar = applyRecordService.findOne(applyRecordId);
				String turnoverUserId = ValidateUtils.filter(request.getParameter("turnoverUserId"));
				noticeInfoService.changeUser(ar, token, turnoverUserId, userId, user.getCnName());
				List<NoticeInfo> saveList = new ArrayList<NoticeInfo>();
				NoticeInfo myNoticeInfo = service.findByApplyrecordId(applyRecordId, userId, "1");
				if(myNoticeInfo == null) {//本人还未参会过，新建参会通知
					NoticeInfo ni = new NoticeInfo();
					ni.setStatus(5);
					ni.setType(1);
					ni.setApplyRecordId(entity.getApplyRecordId());
					ni.setNoticeUserId(userId);
					ni.setTurnoverUserId(turnoverUserId);
					saveList.add(ni);
				}
				NoticeInfo turnoverUserNoticeInfo = service.findByApplyrecordId(applyRecordId, turnoverUserId, "1");
				turnoverUserNoticeInfo.setStatus(4);//转交人通知状态改为4（代参会邀请得到确认）
				saveList.add(turnoverUserNoticeInfo);
				noticeInfoService.save(saveList);
				super.delete(id);//删除代参会确认通知
			}else if("8".equals(nStatus)) {//代参会遭拒
				String turnoverUserId = ValidateUtils.filter(request.getParameter("turnoverUserId"));
				NoticeInfo turnoverUserNoticeInfo = service.findByApplyrecordId(applyRecordId, turnoverUserId, "1");
				turnoverUserNoticeInfo.setStatus(8);//转交人通知状态改为8（代参会邀请被拒绝）
				turnoverUserNoticeInfo.setReason(reason);
				super.editSave(turnoverUserNoticeInfo);
				super.delete(id);
			}else {
				entity.setReason(reason);
			    entity.setStatus(Integer.valueOf(nStatus));
			    if(StringUtils.isNotBlank(attendWay)) entity.setAttendWay(Integer.valueOf(attendWay));
			    super.editSave(entity);
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
			failureMap.put("i18NCode", "oa.meeting.savefalse");
			return OperationResult.buildFailureResult("保存失败",failureMap);
		}
    	failureMap.put("i18NCode", "oa.meeting.savesuccess");
    	return OperationResult.buildSuccessResult("保存成功",failureMap);
    }

    /**
     * 编辑页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/editShow", method = RequestMethod.GET)
    public Map<String, Object> editShow(HttpServletRequest request) {
        String id = ValidateUtils.filter(request.getParameter("id"));
        Map<String, Object> result = new HashMap<>();
        NoticeInfo noticeInfo = this.service.findOne(id);
        if(noticeInfo == null) {
        	result.put("entityIsDelete", true);
        }else {
        	result.put("entityIsDelete", false);
        	result.put("entity", noticeInfo);
        }
        return result;
    }
    
    /**
     * 保存/修改
     *
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/turnoverSave", method = RequestMethod.POST)
    public OperationResult turnoverSave(HttpServletRequest request, @ModelAttribute("entity") NoticeInfo entity) {
    	Map failureMap = new HashMap();
    	List<Map<String,Object>> unInviteUserIdsAndNames=new ArrayList<>();
    	try {
    		if(entity == null) { 
    			failureMap.put("i18NCode", "oa.meeting.tip8");
    			return OperationResult.buildFailureResult("该会议已取消或变更",failureMap);
    		}
			WebUser user = WebUtils.getCurrentUser();
			String corpId = user.getCorpId();
			String token = user.getJwtToken();
			String turnoverUserId = user.getUserId();
			ApplyRecord ar = applyRecordService.findOne(entity.getApplyRecordId());
			if(ar == null) {
				failureMap.put("i18NCode", "oa.meeting.datadelsuccess");
				return OperationResult.buildFailureResult("当前数据已删除",failureMap);
			}
			//查询所有参会人
			List<String> aruList = applyRecordService.getApplyRecordUserList(ar, user.getJwtToken());
			//邀请
			String jsonStrInviteUser = StringUtils.null2String(request.getParameter("jsonStrInviteUser"));
			if(StringUtils.isNotBlank(jsonStrInviteUser)){
				//已转交出去不参会的人
				List<String> turnoverUseIds = noticeInfoService.getTurnoverUseIds(ar.getId(), corpId);
				//被邀请参会的人
				List<String> inviteUserIds = noticeInfoService.getInviteUserIds(jsonStrInviteUser, aruList, turnoverUseIds);
				unInviteUserIdsAndNames=noticeInfoService.getUnInviteUserIdsAndNames(jsonStrInviteUser, aruList, turnoverUseIds);
				noticeInfoService.addNoticeInfo(inviteUserIds, ar.getId(), turnoverUserId, corpId);
				applyRecordService.addAttendUser(ar, inviteUserIds, corpId, token);
				noticeInfoService.sendMessageToTurnoverUser(request, ar, user.getUserId(), inviteUserIds, corpId, TOKEN);
			}
			//代参会
			String isAttendMeeting = StringUtils.null2String(request.getParameter("isAttendMeeting"));
			if("1".equals(isAttendMeeting)) {
				String jsonStrReceiveUser = StringUtils.null2String(request.getParameter("jsonStrReceiveUser"));
				String receiveUserId = "";
				if(StringUtils.isNotBlank(jsonStrReceiveUser)) {
					Map<String, String> map = noticeInfoService.getUserIdAndName(jsonStrReceiveUser);
					receiveUserId = map.get("id");
					if(turnoverUserId.equals(receiveUserId)) {
						failureMap.put("i18NCode", "oa.meeting.tip9");
						return OperationResult.buildFailureResult("代参会人不能选自己",failureMap);
					}
					if(StringUtils.isNotBlank(entity.getReceiveUserId())) {
						failureMap.put("i18NCode", "oa.meeting.tip10");
						return OperationResult.buildFailureResult("该会议您已转交他人",failureMap);
					}
					if(noticeInfoService.findByTurnoverUserId(entity.getApplyRecordId(), receiveUserId) != null) {
						failureMap.put("i18NCode", "oa.meeting.tip11");
						return OperationResult.buildFailureResult("该用户已转交他人代替参会，请重新选择",failureMap);
					}
					entity.setReceiveUserId(receiveUserId);
				}
				//通知状态改为6
				entity.setStatus(6);
				entity.setReason(null);
				//转交人可查看通知，新建转交人通知数据
				NoticeInfo receiveNi = new NoticeInfo();
				receiveNi.setStatus(7);
				receiveNi.setType(2);
				receiveNi.setApplyRecordId(entity.getApplyRecordId());
				receiveNi.setNoticeUserId(receiveUserId);
				receiveNi.setTurnoverUserId(turnoverUserId);
				super.editSave(receiveNi);
				List<String> newUserIdList = new ArrayList<String>();
				newUserIdList.add(receiveUserId);
				if(ar.getIsSigned() == 1) this.signedInfoService.addSignedInfo(newUserIdList, ar.getId(), corpId);
				noticeInfoService.sendMessageToTurnoverUser(request, ar, user.getUserId(), newUserIdList, corpId, TOKEN);
				super.editSave(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
			failureMap.put("i18NCode", "oa.meeting.invitedfalse");
			return OperationResult.buildFailureResult("邀请失败",failureMap);
		}
    	failureMap.put("i18NCode", "oa.meeting.invitedsuccess");
    	failureMap.put("data",unInviteUserIdsAndNames);
        return OperationResult.buildSuccessResult("邀请成功",failureMap);
    }

    /**
     * 保存/修改
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public OperationResult delete(@RequestParam("ids") String... ids) {
        //状态
        return this.service.deleteNoticeInfo(ids);
    }
    
    /**
	 * 获取列表数据(分页)
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getReceiptStatistics", method = RequestMethod.GET)
    public Page getReceiptStatistics(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		//会议id
        String applyrecordId = ValidateUtils.filter(request.getParameter("applyrecordId"));
        //参会情况
        String noticeType = ValidateUtils.filter(request.getParameter("noticeType"));
        String userName = request.getParameter("userName");
		return this.service.getReceiptStatistics(pageable, applyrecordId, noticeType, userName, corpId);
    }
	
    @RequestMapping(value = "/invitedHistory", method = RequestMethod.GET)
    public OperationResult getInvitedHistory(@RequestParam("applyRecordId") String applyRecordId) {
    	WebUser user = WebUtils.getCurrentUser();
    	String userId=user.getUserId();
		String corpId = user.getCorpId();
    	Map<String,Object> paramMap= new HashMap<String,Object>();
    	paramMap.put("corpId", corpId);
    	paramMap.put("inviter", userId);
    	paramMap.put("applyRecordId", applyRecordId);
    	String sql="select n.notice_User_Id noticeUserId,su.user_name userName from oa_meeting_notice_info n inner join sys_user su on n.apply_Record_Id=:applyRecordId and su.id=n.notice_User_Id and inviter=:inviter and n.corp_Id=:corpId and type=1";
    	
    	List<Map> returnList=noticeInfoService.findByListNativeQuery(sql, null,paramMap);
        //状态
        return OperationResult.buildSuccessResult(returnList);
    }
	
	
	
}
